﻿using System;
using System.Collections.Generic;
using System.Text;

namespace EnvSafe.Comm.Ryder
{
    /// <summary>
    /// 锐意GasBoard设备的应用层，该应用层应配合SerialPortTransLayer使用
    /// </summary>
    public class RyderAppLayer : AppLayerBase
    {
        protected override void Initialize()
        {
            //
            TimeoutCircle = Utility.TryGetSetting("SyncFrameTimeoutCircle", Settings, 5);
            NeedItemsByAddress(); //默认的项集合是按名称索引（Items），此处要求构建按地址索引的冗余（ItemsByAddress）
            SendFrame = new byte[4];
            SendFrame[0] = 0x11;
            SendFrame[1] = 0x01;
            SendFrame[2] = 0x01;
            SendFrame[3] = 0xED;
        }

        public int TimeoutCircle { get; set; }
        int continueCounter = 0;
        /// <summary>
        /// 发送帧模板
        /// </summary>
        byte[] SendFrame;

        public override long AddressNormalize(string PlainText)
        {
            throw new NotImplementedException();
        }

        public override byte[] GetHandshake()
        {
            return null;
        }

        public override byte[] GetWriteRequest(string ItemName, object Value)
        {
            // 目前仅实现读取
            return null;
        }

        public override List<byte[]> GetReadRequests()
        {
            var result = new List<byte[]>();
            result.Add(SendFrame);
            return result;
        }

        public override byte[] HandleData(byte[] Data)
        {
            if (Data.Length > 1)
            {
                var len = Data[1];
                if (Data.Length >= len + 3)
                {
                    if (Data[0] == 0x16)
                    {
                        var cnt = (Data[1] - 2) / 2;
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < cnt; i++)
                        {
                            var idx = 3 + i * 2;
                            var rev = new byte[] { Data[idx + 1], Data[idx] };
                            // 以索引为地址，判断变量是否声明，若是则赋值
                            if(ItemsByAddress.ContainsKey(i.ToString())) ItemsByAddress[i.ToString()].ValueCache = BitConverter.ToInt16(rev, 0);
                        }
                    }
                    // error handler

                    //清理
                    continueCounter = 0;
                    return null;
                }
                return Data;
            }
            if (continueCounter > TimeoutCircle)
            {
                //清理
                continueCounter = 0;
                return null;
            }
            else
            {
                return Data;
            }
        }
    }
}
